import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/page/home'
import Login from '@/page/login'
import star from '@/page/star'
import Publicevent from '@/page/publicevent'
Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home,
      meta: {
        requiresAuth: true,
        forcode: true
      }
    },
    {
      path: '/login',
      name: 'Login',
      component: Login
    },
    {
      path: '/star',
      name: 'star',
      component: star,
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/publicevent',
      name: 'Publicevent',
      component: Publicevent,
      meta: {
        requiresAuth: true
      }
    }
  ]
})

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.forcode)) {
    console.log(window.location)
    if (window.location.search){
      window.location.href = window.location.origin + window.location.pathname + '#/login?redirect=%2F' + '&' +window.location.search.substring(1)
    }
    // next({
    //   path: '/login'+ window.location.search,
    //   query: {
    //     redirect: to.fullPath
    //   }
    // })
  }

  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (localStorage.getItem('userToken')) {
      next()
    } else {
      next({ path: '/login', query: { redirect: to.fullPath } })
    }
  } else {
    next() // 确保一定要调用 next()
  }
})

export default router
